/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cip.esymons.general.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.sql.DataSource;

/**
 *
 * @author Gilmar Montoya
 */
public class InterceptorAuditor {

    private static final Logger logger = Logger.getLogger(
            "org.cip.esymons.general.util.InteceptorAuditor");
    private static Connection conn;
    private static PreparedStatement ps;
    @Resource(name = "jdbc/esymons")
    private DataSource jdbcEsymons;

    @AroundInvoke
    public Object profile(InvocationContext ctx) throws Exception {
        long startTime = 0;
        try {
            System.out.println("Ingreso al Interceptor");
            startTime = new Date().getTime();
//            try {
//                UsuarioWebController uw = (UsuarioWebController) ControladorAbstracto.getBean("uw");
//                uw.limpiar();
//                DatosController datosController = ctx.getTarget().getClass().getAnnotation(DatosController.class);
//                if (datosController != null) {
//                    String controllers = datosController.nombresFacesConfig();
//                    StringTokenizer st = new StringTokenizer(controllers, ",");
//                    while (st.hasMoreTokens()) {
//                        String controller = st.nextToken().trim();
//                        uw.agregar(controller);
//                    }
//                }
//            } catch (Exception ex) {
//                System.out.println("Error interceptor");
//            }
            return ctx.proceed();
        } finally {
            long dur = System.currentTimeMillis() - startTime;
            String m = ctx.getTarget().getClass().getName() + "." +
                    ctx.getMethod().getName();
//            log(m, startTime, dur);
            System.out.println("Salida Interceptor: dur:" + dur);
        }
    }

    private DataSource getJdbcEsymons() {
        return jdbcEsymons;
    }

    /** registrar en la base de datos */
    private void log(String metodo, long startTime, long dur) {
        if (ps == null) {
            try {
                conn = getJdbcEsymons().getConnection();
                ps = conn.prepareStatement(
                        "insert into auditoria" +
                        "(METODO, TIEMPO_INICIO, DURACION, ALEATORIO) " +
                        "values(?, ?, ?, ?)");
            } catch (Exception ex) {
                logger.warning(
                        "InterceptorAuditor: Error al preparar la sentencia: " +
                        metodo + ", " + dur + "ms:" + ex.getClass().getSimpleName() +
                        ": " + ex.getMessage());
                return;
            }
        }
        if (dur >= 500) {
            try {
                ps.setString(1, metodo);
                ps.setLong(2, startTime);
                ps.setLong(3, dur);
                ps.setLong(4, (long) (Math.random() * new Date().getTime()));
                ps.executeUpdate();
            } catch (Exception ex) {
                logger.warning("InterceptorAuditor: " + metodo + ", " + dur +
                        "ms:" + ex.getClass().getSimpleName() + ": " +
                        ex.getMessage());
            }
        }
    }
}
